<template>
  <div class="test-page">
    <div class="test-header">
      <h1>🧪 核心功能测试</h1>
      <p>验证AI图文管理系统的核心功能是否正常工作</p>
    </div>

    <div class="test-controls">
      <el-button 
        type="primary" 
        size="large"
        :loading="isRunning"
        @click="runTests"
        :disabled="isRunning"
      >
        <el-icon><PlayFilled /></el-icon>
        {{ isRunning ? '模拟测试运行中...' : '开始模拟测试' }}
      </el-button>
      
      <el-button 
        type="success" 
        size="large"
        :loading="isIntegrationRunning"
        @click="runIntegrationTests"
        :disabled="isIntegrationRunning || isRunning"
      >
        <el-icon><Connection /></el-icon>
        {{ isIntegrationRunning ? '集成测试运行中...' : '开始集成测试' }}
      </el-button>
      
      <el-button 
        v-if="testResults.length > 0"
        @click="clearResults"
        :disabled="isRunning || isIntegrationRunning"
      >
        <el-icon><RefreshLeft /></el-icon>
        清空结果
      </el-button>
    </div>

    <div class="test-progress" v-if="isRunning">
      <el-progress 
        :percentage="progressPercentage" 
        :status="progressStatus"
        :stroke-width="8"
      />
      <p class="progress-text">{{ currentTestName }}</p>
    </div>

    <div class="test-results" v-if="testResults.length > 0">
      <div class="results-summary">
        <el-card>
          <div class="summary-stats">
            <div class="stat-item">
              <span class="stat-label">总测试数</span>
              <span class="stat-value">{{ testResults.length }}</span>
            </div>
            <div class="stat-item success">
              <span class="stat-label">通过</span>
              <span class="stat-value">{{ passedCount }}</span>
            </div>
            <div class="stat-item error">
              <span class="stat-label">失败</span>
              <span class="stat-value">{{ failedCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">成功率</span>
              <span class="stat-value">{{ successRate }}%</span>
            </div>
          </div>
        </el-card>
      </div>

      <div class="results-list">
        <el-card v-for="result in testResults" :key="result.name" class="result-card">
          <div class="result-header">
            <div class="result-title">
              <el-icon 
                :class="getStatusIcon(result.status)"
                :color="getStatusColor(result.status)"
                size="20"
              >
                <component :is="getStatusIcon(result.status)" />
              </el-icon>
              <span>{{ result.name }}</span>
            </div>
            <div class="result-meta">
              <el-tag 
                :type="getStatusTagType(result.status)"
                size="small"
              >
                {{ getStatusText(result.status) }}
              </el-tag>
              <span v-if="result.duration" class="duration">
                {{ result.duration }}ms
              </span>
            </div>
          </div>
          
          <div class="result-message">
            <p>{{ result.message }}</p>
          </div>
        </el-card>
      </div>
    </div>

    <div class="test-info" v-if="!isRunning && testResults.length === 0">
      <el-empty description="点击开始测试按钮运行核心功能测试">
        <template #image>
          <el-icon size="100" color="#409EFF"><TestTube /></el-icon>
        </template>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  PlayFilled, 
  RefreshLeft, 
  SuccessFilled, 
  CircleCloseFilled, 
  Loading,
  TestTube,
  Connection
} from '@element-plus/icons-vue'
import { testRunner } from '@/utils/test-runner'
import { integrationTest } from '@/utils/integration-test'

// 响应式数据
const isRunning = ref(false)
const isIntegrationRunning = ref(false)
const testResults = ref<Array<{
  name: string
  status: 'pending' | 'running' | 'success' | 'error'
  message: string
  duration?: number
}>>([])
const currentTestName = ref('')
const progressPercentage = ref(0)

// 计算属性
const passedCount = computed(() => 
  testResults.value.filter(r => r.status === 'success').length
)

const failedCount = computed(() => 
  testResults.value.filter(r => r.status === 'error').length
)

const successRate = computed(() => {
  if (testResults.value.length === 0) return 0
  return Math.round((passedCount.value / testResults.value.length) * 100)
})

const progressStatus = computed(() => {
  if (failedCount.value > 0) return 'exception'
  if (passedCount.value === testResults.value.length && testResults.value.length > 0) return 'success'
  return undefined
})

// 方法
const runTests = async () => {
  isRunning.value = true
  testResults.value = []
  progressPercentage.value = 0
  currentTestName.value = '准备测试...'
  
  try {
    // 模拟测试运行过程
    const testNames = [
      '图片上传功能',
      'AI识别功能', 
      '搜索筛选功能',
      '文案生成功能',
      '图片扩展功能',
      '图文组合功能',
      '错误处理机制',
      '用户体验流程'
    ]
    
    for (let i = 0; i < testNames.length; i++) {
      currentTestName.value = `正在测试: ${testNames[i]}`
      progressPercentage.value = Math.round(((i + 1) / testNames.length) * 100)
      
      // 模拟测试执行时间
      await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000))
      
      // 模拟测试结果（大部分成功，少数失败）
      const success = Math.random() > 0.2 // 80%成功率
      
      testResults.value.push({
        name: testNames[i],
        status: success ? 'success' : 'error',
        message: success ? '测试通过' : '模拟测试失败',
        duration: Math.round(1000 + Math.random() * 2000)
      })
    }
    
    currentTestName.value = '测试完成'
    
    // 显示测试完成消息
    if (failedCount.value === 0) {
      ElMessage.success(`所有 ${testResults.value.length} 项测试均通过！`)
    } else {
      ElMessage.warning(`${passedCount.value}/${testResults.value.length} 项测试通过`)
    }
    
  } catch (error) {
    console.error('测试运行失败:', error)
    ElMessage.error('测试运行失败，请检查控制台')
  } finally {
    isRunning.value = false
  }
}

const runIntegrationTests = async () => {
  isIntegrationRunning.value = true
  testResults.value = []
  progressPercentage.value = 0
  currentTestName.value = '准备集成测试...'
  
  try {
    ElMessage.info('开始运行集成测试，这将测试实际的API接口')
    
    // 运行集成测试
    const { success, results } = await integrationTest.runIntegrationTests()
    
    // 更新测试结果
    testResults.value = results.map(result => ({
      name: result.name,
      status: result.status,
      message: result.message,
      duration: result.duration
    }))
    
    progressPercentage.value = 100
    currentTestName.value = '集成测试完成'
    
    // 显示测试完成消息
    if (success) {
      ElMessage.success(`所有 ${results.length} 项集成测试均通过！`)
    } else {
      const passedCount = results.filter(r => r.status === 'success').length
      ElMessage.warning(`${passedCount}/${results.length} 项集成测试通过`)
    }
    
  } catch (error) {
    console.error('集成测试运行失败:', error)
    ElMessage.error('集成测试运行失败，请检查后端服务是否启动')
  } finally {
    isIntegrationRunning.value = false
  }
}

const clearResults = () => {
  testResults.value = []
  progressPercentage.value = 0
  currentTestName.value = ''
}

const getStatusIcon = (status: string) => {
  switch (status) {
    case 'success': return 'SuccessFilled'
    case 'error': return 'CircleCloseFilled'
    case 'running': return 'Loading'
    default: return 'Loading'
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'success': return '#67C23A'
    case 'error': return '#F56C6C'
    case 'running': return '#409EFF'
    default: return '#909399'
  }
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'success': return 'success'
    case 'error': return 'danger'
    case 'running': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'success': return '通过'
    case 'error': return '失败'
    case 'running': return '运行中'
    default: return '等待'
  }
}

// 生命周期
onMounted(() => {
  console.log('测试页面已加载')
})
</script>

<style scoped>
.test-page {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-header {
  text-align: center;
  margin-bottom: 32px;
}

.test-header h1 {
  font-size: 32px;
  color: #303133;
  margin-bottom: 8px;
}

.test-header p {
  font-size: 16px;
  color: #606266;
}

.test-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 32px;
}

.test-progress {
  margin-bottom: 32px;
}

.progress-text {
  text-align: center;
  margin-top: 8px;
  color: #606266;
  font-size: 14px;
}

.test-results {
  margin-top: 32px;
}

.results-summary {
  margin-bottom: 24px;
}

.summary-stats {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-item.success .stat-value {
  color: #67C23A;
}

.stat-item.error .stat-value {
  color: #F56C6C;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-card {
  transition: all 0.3s ease;
}

.result-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  font-size: 16px;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.duration {
  font-size: 12px;
  color: #909399;
}

.result-message {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.test-info {
  margin-top: 64px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .test-page {
    padding: 16px;
  }
  
  .test-header h1 {
    font-size: 24px;
  }
  
  .summary-stats {
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .result-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>